<?php
/**
 * @Name  : NodeLogic.php
 * @Author: yashuai
 */

namespace App\Http\Logic\Rbac;

use App\Http\Logic\BaseLogic;
use App\Http\Model\ConstCode;
use App\Http\Model\Rbac\NodeModel;
use App\Http\Model\Rbac\UserModel;
use HugCode\PhpUnits\Utils\UtilArray;

class NodeLogic extends BaseLogic
{

    /**
     * 添加
     * @return int
     */
    public function create()
    {
        return NodeModel::newInsert($this->getParamsTableData());
    }

    /**
     * 更新
     * @return int
     * @throws \App\Exceptions\ApiException
     */
    public function update()
    {
        $info = NodeModel::getInfo($this->params['NodeID'], 'NodeID');
        if (empty($info)) {
            _throw(106001);
        }
        $data = $this->getParamsTableData($info);
        return NodeModel::query()->where(['NodeID' => $this->params['NodeID']])->update($data);
    }


    /**
     * 删除
     * @return int
     * @throws \App\Exceptions\ApiException
     */
    public function delete()
    {
        $info = NodeModel::getInfo($this->params['NodeID'], 'NodeID');
        if (empty($info)) {
            _throw(106001);
        }

        if ($info['NodeStatus'] == ConstCode::BASIC_STATUS_DELETE) {
            return 0;
        }

        return NodeModel::query()->where(['NodeID' => $this->params['NodeID']])->update([
            'NodeStatus' => ConstCode::BASIC_STATUS_DELETE,
        ]);
    }

    /**
     * @Desc 获取用户所有菜单节点树
     * @param boolean $selectButton 是否查询按钮
     * @return array
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function getUserNode($selectButton=false)
    {
        $info   = UserModel::userExist($this->params['UserID'], true);
        $select = [
            'NodeID as menuId',
            'NodeName as title',
            'ParentID as parentId',
            'ControllerName',
            'ActionName',
            'NodeIcon as icon',
            'NodeOrder'
        ];
        $where  = [
            ['NodeShowType', '=', ConstCode::IS_YES],
            ['NodeStatus', '=', ConstCode::BASIC_STATUS_NORMAL],
        ];
        if($selectButton === false){
            $where[] = ['NodeType', '=', ConstCode::NODE_TYPE_MENU];
        }
        $query  = NodeModel::query()->where($where)->select($select)->orderBy('NodeOrder', 'ASC');
        if ($info['IsSuper'] !== ConstCode::IS_YES) {
            $joinSub = NodeModel::getUserNodeIDArray($this->params['UserID']);
            $query->whereIn('NodeID', $joinSub);
        }
        return $query->get()->keyBy('menuId')->toArray();

    }

    /**
     * @Desc 获取用户的后台菜单树
     * @return array
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function getUserAdminNodeTree()
    {
        $node = $this->getUserNode();
        foreach ($node as &$val) {
            $val['hide'] = false;
            if ($val['parentId'] != 0) {
                $val['path'] = $val['component'] = "/" . $val['ControllerName'] . "/" . $val['ActionName'];
                unset($val['ControllerName'], $val['ActionName']);
            }
        }
        $node = UtilArray::listToTree($node, 'menuId', 'parentId', 'children');
        foreach ($node as &$val) {
            if ($val['parentId'] == 0) {
                if (isset($val['children'])) {
                    $val['component'] = '';
                    $val['path']      = "/" . $val['ControllerName'];
                } else {
                    $val['path'] = $val['component'] = "/" . $val['ControllerName'] . "/" . $val['ActionName'];
                }
                unset($val['ControllerName'], $val['ActionName']);
            }
        }
        return array_merge([
            [
                'menuId'    => 0,
                'parentId'  => 0,
                'title'     => "首页",
                'hide'      => false,
                'icon'      => "el-icon-s-home",
                'path'      => "/home/index",
                'component' => "/home/index",
                'children'  => []
            ]
        ], $node);
    }

    /**
     * @Desc   数据转为表结构数据
     * @param array $info
     * @return array
     * @author yashuai
     */
    private function getParamsTableData($info = [])
    {
        return [
            'NodeName'       => $this->params['NodeName'],
            'ParentID'       => $this->getRightParentID(_array_field($this->params, 'ParentID', 0), $info),
            'ControllerName' => $this->params['ControllerName'],
            'ActionName'     => $this->params['ActionName'],
            'EventType'      => $this->params['ControllerName'] . '.' . $this->params['ActionName'],
            'NodeType'       => $this->params['NodeType'],
            'NodeShowType'   => $this->params['NodeShowType'],
            'NodeStatus'     => ConstCode::BASIC_STATUS_NORMAL,
            'NodeIcon'       => _array_field($this->params, 'NodeIcon', ''),
            'NodeOrder'      => $this->params['NodeOrder'],
        ];
    }

    /**
     * 获取正确的父ID
     * @param       $parentID
     * @param array $info
     * @return int
     */
    public function getRightParentID($parentID, $info = [])
    {
        if (empty($parentID)) {
            return 0;
        }
        if (!empty($info) && is_array($info)) {
            return !empty($info['ParentID']) && $info['ParentID'] == $parentID ? $parentID : 0;
        }
        $info = NodeModel::getInfo($parentID, 'NodeID');

        return !empty($info) ? $parentID : 0;
    }

}
